<template>
  <div class="multi-player">
      <div v-if="open" style="position:absolute;right:33px;bottom:65px;z-index:999">
          <el-date-picker v-model="recordDate" format="yyyy/MM/dd" value-format="yyyy/MM/dd" type="date" size="normal" placeholder="选择日期时间" @change="handlerChooseDateClick">
          </el-date-picker>
      </div>
    <div v-loading="loading" element-loading-text="正在读取摄像头录像" element-loading-background="rgba(0, 0, 0, 0.8)"
    element-loading-spinner="el-icon-loading" ref="container" class="container h100" :style="{ width: width }"></div>

  </div>
</template>

<script>
import {
  startPlay,
  stopPlay,
  getStreaminfo,
  playback,
  playbackPause,
  playbackReplay,
  playbackSeek,
  playbackSpeed,
  playbackStop,
} from '@/api/iot/channel';
import { getDevRecord } from "@/api/iot/record";
import { ptzdirection, ptzscale } from '@/api/iot/sipdevice';

export default {
  name: 'SinglePlayer',
  mixins: [],
  components: {},
  props: {
    videoParam: {
      type: Object,
      default: function () {
        return null;
      },
    },
    //宽度
    width: String,
  },
  data() {
    return {
        //视频loading
        loading:false,
        deviceId:'',
        channelId:'',
        streamId:'',
        recordDate:null,
        open:false
    };
  },
  computed: {},
  watch: {
    videoParam: {
      handler: async function (n, o) {
        //只要监听到外部的切换，就将当前流停掉
        this.stopPlay();
        //重新创建播放器
        this.create();
        //然后再赋值播放
        if(!n.deviceId.includes('time') && !n.channelId.includes('time')){
            this.deviceId = n.deviceId;
            this.channelId = n.channelId;
            this.play();
        }else{
            this.$message({
            type: 'warning',
            message: '没有在线通道'
        })
        }
      },
      deep: true
    },
    width: {
      handler: function (n, o) {
        this.$nextTick(() => {
          this.create();
        });
      }
    },
  },
  created() {
  },
  mounted() {
  },
  beforeDestroy() {
    //   this.stopPlay();
    //   this.stopPlayBack();
  },
  methods: {
     async create(type) {
      this.$jessibucaPro && await this.$jessibucaPro.destroy();
      const baseConfig = {
        container: this.$refs.container,
        videoBuffer: 0.1, // 缓存时长
        videoBufferDelay: 0.2, //
        loadingText: '加载中',
        decoder: '/js/jessibuca-pro/decoder-pro.js',
        isResize: false,
        isFlv: true,
        debug: false,
        useMSE: false,
        useSIMD: true,
        debugLevel: 'debug',
        showBandwidth: true, // 显示网速
        showPerformance: false, // 显示性能
        showPlaybackOperate:true,
      }
      let config1 = {
        ...baseConfig,
        ptzZoomShow:true,
         operateBtns: {
          fullscreen: true,
          screenshot: true,
          play: true,
          audio: true,
          record: true,
          ptz: true,
          performance: true,
        },
        ptzClickType: 'mouseDownAndUp',
        extendOperateBtns:[{
            name:'record',
            index:10,
            iconTitle:'视频回播',
            icon:'',
            iconHover:'',
            activeIcon:'',
            click:async ()=>{
                this.open=true;
            }
        }],
      }
      let config2 ={
        ...baseConfig,
          operateBtns: {
          fullscreen: true,
          screenshot: true,
          hiddenAutoPause:true,
          play: true,
          audio: true,
          record: true,
          performance: true,
        },
        ptzClickType: 'mouseDownAndUp',
        extendOperateBtns:[{
            name:'record',
            index:10,
            iconTitle:'视频直播',
            icon:'',
            iconHover:'',
            click:async ()=>{
                await this.create();
                this.play();
            }
        }],
      }
      const jessibucaPro = new JessibucaPro(type==1?config2:config1);

      jessibucaPro.on('ptz', (d) => {
          console.log(d)
        switch (d) {
          case 'up':
            this.ptzDirection(0, 1);
            break;
          case 'down':
            this.ptzDirection(0, 2);
            break;
          case 'left':
            this.ptzDirection(2, 0);
            break;
          case 'right':
            this.ptzDirection(1, 0);
            break;
          case 'zoomExpand':
            this.ptzScale(1);
            break;
          case 'zoomNarrow':
            this.ptzScale(2);
            break;
          case 'stop':
            this.ptzDirection(0, 0);
            this.ptzScale(0);
            break;
        }
      });
      jessibucaPro.on("pause",  (flag)=> {
        this.$streamId &&  this.pausePlayBack();
      })
      jessibucaPro.on("play",  (flag) =>{
        this.$streamId && this.replayPlayBack();
      })
      jessibucaPro.on("playbackSeek",(d)=>{
          this.seekPlayBack(d);
      })
      this.$jessibucaPro = jessibucaPro;
    },
    /** 直播 */
    async play() {
      if (this.deviceId && this.channelId) {
        await startPlay(this.deviceId, this.channelId);
        const response = await getStreaminfo(
          this.videoParam.deviceId,
          this.videoParam.channelId
        );
        let res = JSON.parse(response.data);

        console.log('playurl：' + res.playurl);

        this.streamId = res.streamId;
        res.playurl && this.$jessibucaPro.play(res.playurl);
      }
    },
    /** 停止播放直播 */
    async stopPlay(){
        if (this.deviceId && this.channelId) {
            stopPlay(this.deviceId, this.channelId, this.streamId)
        }
    },
    async handlerChooseDateClick(){
        this.open=false;
        await this.create(1)
        this.playBack();
    },
    /** 回播 */
   async playBack(){                 //  2020/1/1
     let date = this.recordDate?new Date(this.recordDate).getTime(): new Date(new Date().toLocaleDateString()).getTime();//yyyy-dd-hh 00:00:00的时间戳
     this.$start = date / 1000;// yyyy-dd-hh 00:00:00时间戳的秒数
     this.$end = Math.floor((date + 24 * 60 * 60 * 1000 - 1) / 1000);// yyyy-dd-hh 23:59:59时间戳的秒数
     this.loading = true;
     const {data:{recordItems}} = await getDevRecord(this.deviceId, this.channelId, {start:this.$start,end:this.$end});
     this.$videoStart = recordItems[0].start;//设置录像开始时间
     if(recordItems && recordItems.length>0){
         //播放时间为第一段录像的开始时间到结束
        const res = await playback(this.deviceId, this.channelId, {start:recordItems[0].start,end:this.$end});
        this.$ssrc = res.data.ssrc;
        this.$streamId = res.data.streamId;
        this.loading = false;
        this.$jessibucaPro.playback(res.data.playurl, {
            playList: recordItems,
            fps: 20
        })

     }else{
        this.$message({
            type: 'warning',
            message: '当前通道没有录像'
        })
     }
   },
   /** 停止回播 */
   stopPlayBack(){
       if (this.deviceId && this.channelId) {
        playbackStop(this.deviceId, this.channelId, this.$ssrc)
       }
   },
   /** 暂停回播 */
   pausePlayBack(){
       if (this.deviceId && this.channelId) {
        playbackPause(this.deviceId, this.channelId, this.$ssrc)
       }
   },
   /** 重新播放回播*/
    replayPlayBack(){
        if (this.deviceId && this.channelId) {
            playbackReplay(this.deviceId, this.channelId, this.$ssrc);
        }
   },
   /** 选时播放 */
   seekPlayBack(time){
      let curTime = this.$start + time.hour * 3600 + time.min * 60 + time.second;
      let range = this.$start + time.hour * 3600 + time.min * 60 + time.second -this.$videoStart;//视频开始时间到当前时间的秒数
      if (this.$ssrc) {
        const query = {
          seek: range,
        }
        if (this.deviceId && this.channelId) {
          playbackSeek(this.deviceId, this.channelId, this.$ssrc, query).then(res => {
          this.$jessibucaPro.setPlaybackStartTime(curTime)
        })
        }
      }
   },
   /** 方向控制 */
    ptzDirection(leftRight, upDown) {
      var data = {
        leftRight: leftRight,
        upDown: upDown,
        moveSpeed: 125,
      };
      if (this.deviceId && this.channelId) {
        ptzdirection(this.deviceId, this.channelId, data);

      }
    },
     //缩放控制
    ptzScale: function (inOut) {
      console.log('云台缩放：' + inOut);
      var data = {
        inOut: inOut,
        scaleSpeed: 30
      }
      ptzscale(this.deviceId, this.channelId, data)
    },
  },
};
</script>
<style lang="scss" scoped>
    .container{
        background: rgba(13, 14, 27, 0.7);
    }
</style>
